from flask import render_template, redirect, request, url_for

from . import bp
from .StuModel import Student

students_info = [

    Student('zs', '18', '男', '河北省承德市'),
    Student('ls', '20', '女', '河北省邯郸市'),
    Student('ww', '22', '男', '河北省石家庄市'),
]


@bp.route('/')
def index():
    return render_template('index.html', students_info=students_info)


@bp.route(rule='/add/', methods=['GET', 'POST'])
def add_stu():
    if request.method == 'GET':
        return render_template('add.html')
    # TODO 将学生对象中数据添加到学生信息列表中
    data = request.values
    stu = Student(data.get('name'),
                  int(data.get('age')),
                  data.get('gender'),
                  data.get('address'))
    students_info.append(stu)
    # return make_response(redirect('index.html'), students_info=students_info)
    return redirect('/stu/')


@bp.route(rule='/update/<s_id>', methods=['GET', 'POST'])
def update_stu(s_id):
    if request.method == 'GET':
        t_stu = ""
        for si in students_info:
            if si.sno == int(s_id):
                t_stu = si
                break
        return render_template('change.html', stu=t_stu)
    # TODO 将学生对象的信息更新到学生信息字典列表中
    for si in students_info:
        if si.sno == s_id:
            data = request.values
            si.name = data.get('name')
            si.age = int(data.get('age'))
            si.gender = data.get('gender')
            si.address = data.get('address')
    return redirect(url_for("stu.index"))


@bp.route("/del/<s_id>")
def del_stu(s_id):
    for e in students_info:
        if e.sno == int(s_id):
            students_info.remove(e)
            break
    return redirect("/stu/")
